package com.qf.interceptor;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.qf.constatns.AuthConstatns;
import com.qf.constatns.OrderConstants;
import com.qf.utils.OrderUtils;
import com.qf.vo.Customer;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.SelectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class DynamicDataSourceInterceptor implements HandlerInterceptor {

    public Integer getTabIndex() {
        return tabInexThreadLocak.get();
    }

    private ThreadLocal<Integer> tabInexThreadLocak = new ThreadLocal<>();

    @Autowired
    private OrderUtils orderUtils;

    /**
     * 1.计算出数据库编号
     * 2、计算出表的编号
     * 3、设置数据源
     *
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 1.获取当前登录的用户
        Customer customer = (Customer) request.getSession().getAttribute(AuthConstatns.AUTH_SESSION);

        // 2.如果当前请求是支付宝调用，不需要再验证是否登录了，直接放行
        String requestURL = request.getRequestURI();

        AntPathMatcher antPathMatcher = new AntPathMatcher();

        // http://4st2zz.natappfree.cc/pay/ali/updateOrder

        // 3.当前请求是否和/ali/updateOrder匹配，如果匹配说明这个请求是ali调用的
        boolean match = antPathMatcher.match("/orderController/updateOrderStatus/**", requestURL);
        boolean match1 = antPathMatcher.match("/orderController/getOrderInfoById/**", requestURL);

        log.debug("match:{}",match);
        log.debug("match1:{}",match1);
        if (match || match1) {
            return true;
        }

        if (customer == null) {
            response.sendRedirect("http://localhost/auth/login.html");
            return false;
        }


        Integer uid = customer.getId();

        log.debug("uid:{}", uid);
        // 2.获取用户id后四位
        Integer lastUid = Integer.parseInt(orderUtils.lastUserId(uid));

        // 3.计算数据库的编号(用户id后四位%数据库的数量)
        Integer dbIndex = (lastUid % OrderConstants.ORDER_DB_SIZE) + 1;

        // 4.创建数据源key
        String dataSourceKey = OrderConstants.ORDER_DB_PRE + dbIndex;

        // 5、设置数据源
        DynamicDataSourceContextHolder.push(dataSourceKey);

        // 6.计算订单的表的编号(在插入的时候才会使用这个值，我在这个地方一起计算出来)
        Integer tabIndex = (lastUid / OrderConstants.ORDER_DB_SIZE % OrderConstants.ORDER_TABLE_SIZE) + 1;

        // 把tabIndex放入到ThreadLocl中,方便Mapper中获取
        tabInexThreadLocak.set(tabIndex);

        log.debug("【DynamicDataSourceInterceptor】当前线程id:{}", Thread.currentThread().getId());
        log.debug("用户Id后四位:{}", lastUid);
        log.debug("数据库的编号是:{}", dbIndex);
        log.debug("数据表的编号是:{}", tabIndex);

        // 7、放行
        return true;
    }
}
